//生产者和消费者模型 —— 线程同步互斥模型
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

int food = 0;

void *pthread_produce(void *arg){
    sleep(3);
    while(1){
        sleep(1);
        pthread_mutex_lock(&mutex);
        printf("正在生产食物...\n");
        food++;
        printf("生产食物完毕...目前的食物总数:%d\n", food);
        pthread_mutex_unlock(&mutex);

        //让生产者执行完毕后给消费者发送信号通知
        pthread_cond_signal(&cond);
    }
}

void *pthread_customer(void *arg){
    while(1){
        sleep(1);
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        //只有执行到wait的时候接收信号才会有作用，如果信号早到了会错失信号
        
        printf("正在消耗食物...\n");
        food--;
        printf("消费食物完毕...目前的食物总数:%d\n", food);
        pthread_mutex_unlock(&mutex);
    }
}


int main(int argc, char const *argv[]){

    //初始化条件变量
    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);
    pthread_t thread1, thread2;
    printf("进程正在运行....\n");
    //使用pthread_create来创建线程
    if(pthread_create(&thread1, NULL, pthread_produce, NULL) != 0){
        printf("pthread_create failed\n");
        return -1;
    }

    if(pthread_create(&thread2, NULL, pthread_customer, NULL) != 0){
        printf("pthread_create failed\n");
        return -1;
    }
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}